package org.example.nettydemo.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Scanner;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {


    /**
     * 连接建立的完成
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        byte[] bytes = "hi,服务端，我是客户端！".getBytes();
        Scanner scanner = new Scanner(System.in);
        while (!"break".equals(scanner.hasNext())) {
            byte[] bytes = scanner.nextLine().getBytes();
            ByteBuf byteBuf = Unpooled.wrappedBuffer(bytes);
            ctx.channel().writeAndFlush(byteBuf);
        }
    }

    /**
     * 读取数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf responseByteBuf= (ByteBuf)msg;
        byte[] responseByte=new byte[responseByteBuf.readableBytes()];
        responseByteBuf.readBytes(responseByte);
        System.out.println(new String(responseByte));
    }


    /**
     * 异常
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }
}
